#include "txtbookdatabuilder.h"

TXTBookDataBuilder::TXTBookDataBuilder(const QString &fileName):BookDataBuilder(fileName),page(new QWebPage)
{
    _bookData = 0;
    page->setViewportSize(QSize(526,600));
    templateFile = Util().loadFile("template\\cover.html");;
}
void TXTBookDataBuilder::parse()
{
    if(this->_bookData!=0)delete this->_bookData;
    this->_bookData = new BookData;
    QFile file(this->_fileName);
    if ( file.open(QFile::ReadOnly )) {
        QTextStream stream( &file );
        QString lines;
        QString line;
        int tmp=1;

        int count = 0;
        while(!stream.atEnd()){
            line = stream.readLine();
            line.append("<br/>");

            tmp = line.length()/39+1;
            count+=tmp;
            if(count>=30||tmp>5){
                page->mainFrame()->setHtml(lines+line);
                if(page->mainFrame()->contentsSize().height()>page->viewportSize().height()){
                    _bookData->getContents()->append(lines);
                    lines.clear();
                    count=0;
                }
                
            }
            lines.append(line);
        }
        _bookData->getContents()->append(lines);
        file.close();
        addCover(_bookData);
        //frame->setHtml("",QUrl(""));
    }
}
QString TXTBookDataBuilder::substract(QString &lines,QString &line){
    return QString::null;
}
void TXTBookDataBuilder::addCover(BookData* bookData)
{
    Util util;
    QString content = util.loadFile("template\\cover.html");
    QFileInfo fileInfo(this->_fileName);

    content = content.replace("${title}",fileInfo.fileName());
    content = content.replace("${author}",fileInfo.owner());
    content = content.replace("${discription}",QString("Total Page %1").arg(bookData->getContents()->count()));

    QDateTime date = fileInfo.created();
    content = content.replace("${date}",date.toString());
    bookData->getContents()->insert(bookData->getContents()->begin(),content);
}
